package jrain.fw.dao.common.transaction;

import java.sql.Connection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import jrain.fw.core.dao.TransactionManager;
import jrain.fw.core.service.Service;
import jrain.fw.core.service.ServiceConst;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.sql.SqlUtils;

@Service(group = ServiceConst.S_DAO_TRANSACTION_MANAGER, module = ServiceConst.M_DAO)
public class DefaultTransactionManager implements TransactionManager {

	private static final ThreadLocal<ConcurrentMap<String, Connholder>> local = new ThreadLocal<ConcurrentMap<String, Connholder>>() {

		@Override
		protected ConcurrentMap<String, Connholder> initialValue() {
			return new ConcurrentHashMap<String, Connholder>();
		}
	};

	public DefaultTransactionManager() {

	}

	public void begin(String dataSourceName, Map<String, Object> data) {
		ConcurrentMap<String, Connholder> map = local.get();
		map.clear();
		Connholder connholder = new Connholder(dataSourceName, data);
		map.putIfAbsent(dataSourceName, connholder);

	}

	@Override
	public Connection getConnection(String dataSourceName, Map<String, Object> data) {
		ConcurrentMap<String, Connholder> map = local.get();
		Connholder connholder = map.get(dataSourceName);
		if (connholder != null) {
			return connholder.getConnection();
		} else {
			return FwUtils.getDataSourceService().getConnection(dataSourceName, data);
		}
	}

	@Override
	public void commit(String dataSourceName) {
		ConcurrentMap<String, Connholder> map = local.get();
		Connholder connholder = map.remove(dataSourceName);
		connholder.commit();
		map.clear();
	}

	@Override
	public void rollback(String dataSourceName) {
		ConcurrentMap<String, Connholder> map = local.get();
		Connholder connholder = map.remove(dataSourceName);
		connholder.rollback();
		map.clear();

	}

	@Override
	public void closeConn(String dataSourceName, Connection conn) {
		ConcurrentMap<String, Connholder> map = local.get();
		Connholder connholder = map.get(dataSourceName);
		if (connholder == null) {
			SqlUtils.closeConn(conn);
		}
	}

}